package com.sgb.merchant.view.activity;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.util.Pair;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.material.tabs.TabLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.link.entity.merchant.ApplyEntity;
import com.sgb.link.router.PathMerchant;
import com.sgb.link.view.widget.CustomXTabLayout;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantActivitySelfApplyListBinding;
import com.sgb.merchant.view.adapter.ApplyListAdapter;
import com.sgb.merchant.viewmodel.SelfApplyViewModel;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 王彬臣
 * @date: 2021/8/26
 * @Description: 投资项目-我的报名列表
 */
@Route(path = PathMerchant.SelfApplyActivity)
public class SelfApplyActivity extends BaseActivity<SelfApplyViewModel, MerchantActivitySelfApplyListBinding> {
    private String[] titles = {"全部", "已上架", "已下架"};
    ;

    private boolean mIsLoadMore;

    private boolean mIsHasSearch;

    Map<String, Object> mMap = new HashMap<>();

    ApplyListAdapter mAdapter;

    List<ApplyEntity> applyEntityList = new ArrayList<>();

    ApplyEntity mEntity;
    private int type;

    @Override
    protected int layoutId() {
        return R.layout.merchant_activity_self_apply_list;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(SelfApplyViewModel.class);
    }

    @Override
    protected void init() {
        mBinding.setClick(this);
        for (String title : titles) {
            mBinding.tabIndustryCategory.addTab(mBinding.tabIndustryCategory.newTab().setText(title));
        }
        initEvent();
        initAdapter();
        initData();
    }

    private void initData() {
        mViewModel.ldData.observe(this, list -> showProjectList(list, mIsLoadMore));
        mViewModel.ldState.observe(this, state -> {
            switch (state) {//0未上架 1已删除 2正常
                case 0:
                    new RoundDialog.Builder(this)
                            .title("温馨提示")
                            .content("该数据状态已发生变化，请刷新后再进行操作。")
                            .cancel("取消")
                            .confirm("确定")
                            .cancelable(false)
                            .confirmCallback(v12 -> {
                                mIsLoadMore = false;
                                getData();
                            }).show();
                    break;
                case 1:
                    MToast.showToast(this, "当前数据已删除");
                    mIsLoadMore = false;
                    getData();
                    break;
                case 2:
                    ActivityJump.startActivity(PathMerchant.InvestmentDetailActivity, Pair.create(RouterKey.NO, mEntity.getItemNo()));
                    break;
            }
        });
        getData();
    }

    private void initEvent() {
        mBinding.tabIndustryCategory.setNormalColor96();
        mBinding.tabIndustryCategory.addOnTabSelectedListener(new CustomXTabLayout.SimpleSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    mMap.remove("status");
                } else if (tab.getPosition() == 1) {
                    mMap.put("status", "0");
                } else if (tab.getPosition() == 2) {
                    mMap.put("status", "1");
                }
                DialogHelper.showProgressDialog(SelfApplyActivity.this, "加载中...").setCanceledOnTouchOutside(true);
                mIsLoadMore = false;
                getData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        mBinding.ivCloseRed.setOnClickListener(v -> {
            mBinding.editSearchRed.setText("");
            if (mIsHasSearch) {
                DialogHelper.showProgressDialog(this, "搜索中").setCanceledOnTouchOutside(true);
                closeKeybord();
                mMap.remove("itemName");
                mIsLoadMore = false;
                getData();
            }
        });
        mBinding.editSearchRed.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mBinding.editSearchRed.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                closeKeybord();
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    mIsHasSearch = true;
                    if (TextUtils.isEmpty(mBinding.editSearchRed.getText().toString())) {
                        MToast.showToast(SelfApplyActivity.this, "请输入项目名称");
                        return true;
                    }
                    DialogHelper.showProgressDialog(SelfApplyActivity.this, "搜索中").setCanceledOnTouchOutside(true);
                    mMap.put("itemName", mBinding.editSearchRed.getText().toString());
                    mIsLoadMore = false;
                    getData();
                }
                return false;
            }
        });
        mBinding.editSearchRed.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    mBinding.ivCloseRed.setVisibility(View.GONE);
                } else {
                    mBinding.ivCloseRed.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void initAdapter() {
        mBinding.displayView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ApplyListAdapter(applyEntityList);
        mAdapter.bindToRecyclerView(mBinding.displayView);

        mAdapter.setBtnOnClickListener(new ApplyListAdapter.BtnOnClickListener() {
            @Override
            public void projectDetail(ApplyEntity entity) {

                type = 0;
                mEntity = entity;
                mViewModel.getState(entity.getItemNo());
            }

            @Override
            public void applyDetail(ApplyEntity entity) {
                type = 1;
                mEntity = entity;
                ActivityJump.startActivity(PathMerchant.ApplyDetailActivity, Pair.create(RouterKey.ID, mEntity.getApplyNo()));
            }
        });
        mBinding.displayView.setAdapter(mAdapter);
        mBinding.refreshLayout.setEnableRefresh(true);
        mBinding.refreshLayout.setEnableLoadMore(true);
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mIsLoadMore = true;
                getData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mIsLoadMore = false;
                getData();
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_back_red) {
            finish();

        } else if (v.getId() == R.id.tv_search) {
            if (mBinding.editSearchRed.getText().toString().equals("")) {
                MToast.showToast(this, "请输入项目名称");
                return;
            }
            DialogHelper.showProgressDialog(this, "搜索中").setCanceledOnTouchOutside(true);
            mIsHasSearch = true;
            mMap.put("itemName", mBinding.editSearchRed.getText().toString());
            closeKeybord();
            mIsLoadMore = false;
            getData();
        }
    }

    private void getData() {
        mViewModel.getDataList(mIsLoadMore, mMap);

    }

    /**
     * 数据
     *
     * @param list
     * @param isLoadMore
     */
    public void showProjectList(List<ApplyEntity> list, boolean isLoadMore) {
        DialogHelper.dismissProgressDialog();
        mBinding.refreshLayout.finishRefresh();
        mBinding.refreshLayout.finishLoadMore();
        if (isLoadMore) {
            if (null != list && list.size() > 0) {
                mBinding.refreshLayout.resetNoMoreData();
                applyEntityList.addAll(list);
            } else {
                mBinding.refreshLayout.finishLoadMoreWithNoMoreData();
            }

        } else {
            applyEntityList.clear();
            if (null != list && list.size() > 0) {
                applyEntityList.addAll(list);
            } else {
                mAdapter.setEmptyView(R.layout.merchant_empty_views);
            }
        }
        mAdapter.notifyDataSetChanged();
    }
}
